package com.jfirer.mvc.resolver.impl;

import com.jfirer.baseutil.reflect.ReflectUtil;
import com.jfirer.dson.Dson;
import com.jfirer.mvc.annotation.RequestBody;
import com.jfirer.mvc.resolver.AbstractParamResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Arrays;

public class RequestBodyResolver extends AbstractParamResolver
{
    private Charset charset;
    private Type    type;

    public RequestBodyResolver(Method method)
    {
        super("first param");
        String value = method.getAnnotation(RequestBody.class).value();
        charset = Charset.forName(value);
        type = method.getGenericParameterTypes()[0];
    }

    private static final ThreadLocal<byte[]> LOCAL = new ThreadLocal<byte[]>()
    {
        @Override
        protected byte[] initialValue()
        {
            return new byte[512];
        }
    };

    @Override
    public Object resolve(HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            InputStream inputStream = request.getInputStream();
            byte[]      array       = LOCAL.get();
            int         available   = inputStream.available();
            if (available >= array.length)
            {
                array = Arrays.copyOf(array, available);
                LOCAL.set(array);
            }
            if (inputStream.read(array) != available)
            {
                throw new IllegalStateException("没有一次读取到所有的字节数据");
            }
            String value = new String(array, 0, available, charset);
            return Dson.fromString(type, value);
        }
        catch (Exception e)
        {
            ReflectUtil.throwException(e);
            return null;
        }
    }
}
